package com.zj.sixtyDayChallenge.array;

import java.util.Arrays;

/**
 * @program: algorithm
 * @description: 有序数组的平方
 * 977 squares-of-a-sorted-array
 * @author: Zhang Bo
 * @create: 2022-12-20 10:41:30
 **/
public class SquaresOfASortedArray {
    public static void main(String[] args) {
        Solution solution = new SquaresOfASortedArray().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * [-4,-1,0,3,10]
         *
         * @param nums
         * @return
         */
        public int[] sortedSquares01(int[] nums) {

            for (int i = 0; i < nums.length; i++) {
                nums[i] = nums[i] * nums[i];
            }
            Arrays.sort(nums);
            return nums;

        }


        /**
         * [-4,-1,0,3,10]
         *
         * @param nums
         * @return
         */
        public int[] sortedSquares(int[] nums) {

            int sub = nums.length - 1;
            int i = 0;
            int j = nums.length - 1;
            int[] newNums = new int[nums.length];
            while (i <= j) {
                int left = nums[i] * nums[i];
                int right = nums[j] * nums[j];
                if (left > right) {
                    newNums[sub--] = left;
                    i++;
                } else {
                    newNums[sub--] = right;
                    j--;
                }
            }
            return newNums;

        }


        public int[] sortedSquares02(int[] nums) {

            int i = 0;
            int j = nums.length - 1;
            int[] res = new int[nums.length];
            int sub = nums.length - 1;
            while (i <= j) {
                int l = nums[i] * nums[i];
                int r = nums[j] * nums[j];
                if (l > r) {
                    res[sub--] = l;
                    i++;
                } else {
                    res[sub--] = r;
                    j--;
                }
            }

            return res;
        }

    }
//leetcode submit region end(Prohibit modification and deletion)

}